package com.zhkj.txg.module.home.vm

import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.zhkj.lib.base.BaseViewModel
import com.zhkj.lib.http.HttpResponse
import com.zhkj.lib.http.ViewModelSubscribeListener
import com.zhkj.txg.module.home.entity.MallResponse
import com.zhkj.txg.module.home.entity.MallShopResponse
import com.zhkj.txg.module.home.model.HomeManager

class MallViewModel(application: Application) : BaseViewModel(application) {
    private val homeManager = HomeManager()
    val mallLiveData = MutableLiveData<HttpResponse<MallResponse>>()
    val mallShopLiveData = MutableLiveData<HttpResponse<MallShopResponse>>()

    private val numb = 20
    var page = 1
        private set

    fun mallData(token: String, restart: Boolean) {
        val listener = object : ViewModelSubscribeListener<MallResponse>(mallLiveData) {
            override fun onSuccess(resp: MallResponse) {
                super.onSuccess(resp)
                page = 1
                if (restart) mallShopList(token, restart)
            }
        }
        val mallData = homeManager.mallData(token, listener)
        dispose.add(mallData)
    }

    fun mallShopList(token: String, restart: Boolean = false) {
        val listener = object : ViewModelSubscribeListener<MallShopResponse>(mallShopLiveData) {
            override fun onSuccess(resp: MallShopResponse) {
                resp.hasMore = resp.data.size >= numb
                resp.loadMore = page > 1
                super.onSuccess(resp)
                page += 1
            }
        }
        if (restart) page = 1
        val mallShopList = homeManager.mallShopList(token, page, numb, listener)
        dispose.add(mallShopList)
    }
}